package com.example.demo.Service.ServerImpl;


import com.example.demo.Service.CustomerService;
import com.example.demo.repository.dao.CustomerDao;
import com.example.demo.repository.domain.Customer;
import com.example.demo.util.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.example.demo.util.MD5.encode;

/**
 * @author ZhangKe
 * @Description
 * @date 2019/7/3 13:12.
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;

    @Override
    public Customer getById(int id) {
        return customerDao.getById(1);
    }

    @Override
    public Customer getByName(String name) {
        return customerDao.getByName(name);
    }

    @Override
    public int register(Customer customer) {
        int count=customerDao.countByName(customer.getCustomerName());
        if (count==0){          //用户不存在
            String password=customer.getCustomerPasswd();
            String salt = ImageUtil.getRandomStr(20);
            customer.setSalt(salt);
            String password_MD5 = encode(password, salt);
            customer.setCustomerPasswd(password_MD5);
            return customerDao.insert(customer);
        }else{
            return 0;       //用户已存在
        }
    }

    @Override
    public int login(String customerName, String password) {
        Customer result=customerDao.getByName(customerName);//用户名：customerName的用户是否存在：null不存在，反之存在
        if (result==null){
            return -1;
        }else{  //用户存在
            String salt = result.getSalt();
            String password_MD5 = encode(password, salt);
            if (password_MD5.equals(result.getCustomerPasswd())){   //用户存在，并且密码正确
                return 1;
            }else{          //用户存在，但是密码不正确
                return 0;
            }
        }
    }

    @Override
    public int update(Customer customer) {
        return customerDao.update(customer);
    }
}
